<?php

namespace app\admin\controller\caiwu;

use app\common\controller\Backend;
use function fast\e;

/**
 * 账单记录
 *
 * @icon  fa fa-bitcoin
 */
class Record extends Backend
{
    /**
     * 账单记录
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null);
            $type = input('type',0);
            if(empty($type)){
                $list = db('bill_record')
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            }else{
                $list = db('bill_record')
                    ->where('type',$type)
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            }


            $data = $list->items();
            foreach ($data as &$item){
                $item['cate_bianhao_1'] = $item['cate_bianhao_2'] = $item['cate_bianhao'];
                $item['user_name'] = '';

                if(!empty($item['user_id'])){
                    $user = db('admin')->find($item['user_id']);
                    $item['user_name'] = $user['name'] ?? '-';

                }

                $category = db('bill_cate')->where('bianhao',$item['cate_bianhao'])->find();
                $item['cate_name'] = $category['cate_name'];
            }
            $result = array("total" => $list->total(), "rows" => $data,"extend"=>[]);

            return json($result);
        }

        return $this->view->fetch();

    }

    /**
     * 添加账单
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if(empty($params['cate_bianhao'])){
                $this->error("请选择账单分类");
            }
            if(empty($params['title'])){
                $this->error("请描述标题");
            }
            if(isset($params['price']) && empty($params['price'])){
                $this->error("金额不为空");
            }

            $params['cate_bianhao'] = trim($params['cate_bianhao']);
            $params['create_time'] =  date("Y-m-d H:i:s");
            $params['update_time'] =  date("Y-m-d H:i:s");
            unset($params['id']);
            $admin_id = getAdminInfo('id');
            $inData = [
                'user_id'=>$admin_id,
                'cate_bianhao'=>$params['cate_bianhao'],
                'type'=>$params['type'],

                'title'=>$params['title'],
                'price'=>$params['price'],
                'remark'=>$params['remark'],
                'create_time'=>date("Y-m-d H:i:s"),
                'update_time'=>date("Y-m-d H:i:s"),
            ];

            db('bill_record')->insertGetId($inData);
            $this->success(__('Add Success'));
        }
        $type = input('type',2);
        if($type ==1){
            $cateData = db('bill_cate')->where('type',1)->select();
        }else{
            $cateData = db('bill_cate')->where('type',2)->select();
        }
        $cateArr = [];
        foreach ($cateData as $one){
            $cateArr[$one['bianhao']] = $one['cate_name'];
        }
        $this->view->assign('id',0);
        $this->view->assign('data',[]);
        $this->view->assign('type',$type);
        $this->view->assign('cate_bianhao',0);
        $this->view->assign('cateData',$cateArr);
        $this->view->assign('type_name',$type == 1 ? "账单收入":"支出账单");
        return $this->view->fetch('addbill');

    }

    /**
     * 编辑账单
     */
    public function edit($ids = null)
    {
        //订单类 或者 进货类的，不可修改金额等数据
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if(empty($params['cate_bianhao'])){
                $this->error("请选择账单分类");
            }
            if(empty($params['title'])){
                $this->error("请描述标题");
            }
            if(isset($params['price']) && empty($params['price'])){
                $this->error("金额不为空");
            }

            $data = db('bill_record')->find($params['id']);
            if(!empty($data['inventory_bianhao']) || !empty($data['order_bianhao'])){
                $upData = [];
                $upData['id'] = $params['id'];
                $upData['remark'] = $params['remark'];
                $upData['update_time'] = date("Y-m-d H:i:s");

                db('bill_record')->update($upData);
            }else{
                $params['cate_bianhao'] = trim($params['cate_bianhao']);
                $params['update_time'] = date("Y-m-d H:i:s");

                db('bill_record')->update($params);
            }

            $this->success("编辑成功");
        }

        $data = db('bill_record')->find($ids);
        $c_time = strtotime($data['create_time']);
        if(time() - $c_time > 3600*10){
            $this->error("过去账单记录不允许随意修改");
        }
        if($data['type'] == 2){
            $cateData = db('bill_cate')->where('type',2)->select();
        }else{
            $cateData = db('bill_cate')->where('type',1)->select();
        }

        $cateArr = [];
        foreach ($cateData as $one){
            $cateArr[$one['bianhao']] = $one['cate_name'];
        }
        $this->view->assign('id',$ids);
        $this->view->assign('data',$data);
        $this->view->assign('type',$data['type']);
        $this->view->assign('cate_bianhao',$data['cate_bianhao']);
        $this->view->assign('cateData',$cateArr);
        $this->view->assign('type_name',$data['type'] == 1 ? "账单收入":"支出账单");
        return $this->view->fetch('addbill');
    }
    /**
     * 获取分类
     */
    public function ajaxCate(){
        $name = input('name','');
        $type = input('type','1');

        $keyField = $this->request->param("keyField");
        $keyValue = $this->request->param("keyValue");

        //        $word = $this->request->param()['q_word'][0];
        $page = $this->request->param('pageNumber');
        $limit = $this->request->param('pageSize');
        $page = $page ? $page : 1;
        $limit = $limit ? $limit : 20;

        $where = [];
        if (!empty($keyValue)) {
            $where[$keyField] = $keyValue;
        }


        $filed = "bianhao as id,cate_name";


        if(empty($name)){
            $total = db('bill_cate')->where('type',$type)->count();
            $data = db('bill_cate')
                ->field($filed)
                ->where('type',$type)
                ->where($where)
                ->order('id desc')
                ->limit($limit)
                ->page($page)
                ->select();
        }else{
            $total = db('bill_cate')->where('type',$type)->field($filed)->where("cate_name like '%{$name}%'")->count();
            $data = db('bill_cate')
                ->field($filed)
                ->where('type',$type)
                ->where($where)
                ->where("cate_name like '%{$name}%'")
                ->order('id desc')
                ->limit($limit)
                ->page($page)
                ->select();
        }

        $reData = ['list'=>[],'total'=>0];
        $list = [];
        foreach ($data as $item){
            $list[] = $item;
        }
        $reData['list'] = $list;
        $reData['total'] = $total;
        echo json_encode($reData);die();
    }

    /**
     * 选择用户
     */
    public function ajaxUser(){
        $name = input('name','');
        $filed = "id,name";

        //        $word = $this->request->param()['q_word'][0];
        $page = $this->request->param('pageNumber');
        $limit = $this->request->param('pageSize');
        $page = $page ? $page : 1;
        $limit = $limit ? $limit : 20;

        if(empty($name)){
            $total = db('admin')->where('id','>',0)->count();
            $data = db('admin')
                ->where('id','>',0)
                ->field($filed)
                ->order('id desc')
                ->limit($limit)
                ->page($page)
                ->select();
        }else{

            $total = db('admin')->where("name like '%{$name}%'")->count();
            $data = db('admin')
                ->field($filed)
                ->where("name like '%{$name}%'")
                ->order('id desc')
                ->limit($limit)
                ->page($page)
                ->select();
        }

        $reData = ['list'=>[],'total'=>0];
        $list = [];
        foreach ($data as $item){
            $item['name'] = $item['id']."|".$item['name'];
            $list[] = $item;
        }
        $reData['list'] = $list;
        $reData['total'] = $total;
        echo json_encode($reData);die();
    }

}
